package com.drive.service.serviceimpl;

import com.drive.bean.Coach;
import com.drive.entity.PageResult;
import com.drive.mapper.CoachMapper;
import com.drive.service.CoachService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 往
 * 教练管理接口实现类
 */
@Service
public class CoachServiceImpl implements CoachService {
    @Autowired
    private CoachMapper coachMapper;

    //新增
    @Override
    public void add(Coach coach,Integer[] studentIds) {
        coachMapper.add(coach);
        //调用setCoachAndStudent方法并传入 students 和 教练id
        setCoachAndStudent(coach.getId(),studentIds);
    }

    //分页查询
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        //调用PageHelper插件
        PageHelper.startPage(currentPage,pageSize);
        //封装数据
        Page<Coach> coachPage = coachMapper.selectByCondition(queryString);
        //返回查询到的总记录数及结果数据
        return new PageResult(coachPage.getTotal(),coachPage.getResult());

    }

    //根据id查询教练基本信息
    @Override
    public Coach findById(Integer id) {
        return coachMapper.findById(id);
    }

    //根据教练id查询所有学员id
    @Override
    public List<Integer> findStudentIdByCoachId(Integer id) {
        return coachMapper.findStudentIdByCoachId(id);
    }

    //编辑教练信息，同时需要更新中间关系表
    @Override
    public void edit(Coach coach, Integer[] studentIds) {
        //1.根据教练id 删除原有的关联关系
        coachMapper.deleteAssciation(coach.getId());
        //2.重新建立关联关系表
        setCoachAndStudent(coach.getId(),studentIds);
        //3.更新教练基本信息
        coachMapper.edit(coach);
    }

    @Override
    public void delete(Integer id) {
        //1.根据id删除关联关系表
        coachMapper.deleteAssciation(id);
        //2.根据id删除基本信息
        coachMapper.deleteById(id);
    }

    @Override
    public List<Coach> findAll() {
        return coachMapper.findAll();
    }

    //设置教练和学员的关联关系
    public void setCoachAndStudent(Integer coachId,Integer[] studentIds){
        if (studentIds!=null&&studentIds.length>0){
            //创建 map 集合存储教练与学员的信息
            Map<String,Integer> map = new HashMap<>();
            //遍历students集合
            for (Integer studentId : studentIds) {
                //存入教练的id
                map.put("coach_id",coachId);
                //存入学员的id
                map.put("student_id",studentId);
                //将 map 数据存入到教练学员中间关系表中
                coachMapper.setCoachAndStudent(map);
            }
        }
    }
}
